package com.itheima.exerciseTest.method30_39.method38;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

//        2.4.1Class类获取成员变量对象的方法
public class Demo {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//        Field[] getFields()                	返回所有公共成员变量对象的数组
        // method1();

//        Field[] getDeclaredFields()        	返回所有成员变量对象的数组
        // method2();

//        Field getField(String name)        	返回单个公共成员变量对象
        // method3();

//        Field getDeclaredField(String name)	返回单个成员变量对象
        // method4();


    }

    private static void method4() throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class className = Class.forName("com.itheima.exerciseTest.method30_39.method38.Student");

        Field declaredField = className.getDeclaredField("money");

        System.out.println(declaredField);


        Constructor constructor = className.getConstructor();

        Student student = (Student) constructor.newInstance();

        declaredField.setAccessible(true);

        System.out.println(declaredField.get(student));

        declaredField.set(student,998);

        int money = (int) declaredField.get(student);

        System.out.println(money);
    }

    private static void method3() throws ClassNotFoundException, NoSuchFieldException {
        Class className = Class.forName("com.itheima.exerciseTest.method30_39.method38.Student");
        Field field = className.getField("name");
        System.out.println(field);
    }

    private static void method2() throws ClassNotFoundException {
        Class className = Class.forName("com.itheima.exerciseTest.method30_39.method38.Student");
        Field[] declaredFields = className.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }
    }

    private static void method1() throws ClassNotFoundException {
        Class className = Class.forName("com.itheima.exerciseTest.method30_39.method38.Student");
        Field[] fields = className.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }
    }
}
